//
//  LSFtpManager.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/26.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSFtpManager.h"

//注意：调用前先确保已经初始化Host
/*[ZBFtpTools ZBFtp_setupInitWithHost:ftpServerAddress
user:ftpUser
psw:ftpUserPwd];*/

@implementation LSFtpManager

- (void)LS_ftpdownloadFileName:(NSString *)fileName Path:(NSString *)ftpUrl Success:(FtpSuccessdownloadBlock)success failuer:(FtpFailloadBlock)failure {
    if (![self isExistUnzipFile:fileName]) {//解压文件不存在
        //创建下载文件夹
        //atxz文件下载路径处理
        NSFileManager *fm = [NSFileManager defaultManager];
        NSString *downFilePath = [NSString stringWithFormat:@"%@%@", NSHomeDirectory(),downloadFilePath];
        BOOL isDir = YES;
        if(![fm fileExistsAtPath:downFilePath isDirectory:&isDir]) {
            [fm createDirectoryAtPath:downFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
       // NSLog(@"downFilePath=%@",downFilePath);
        downFilePath = [NSString stringWithFormat:@"%@/%@.atxz",downFilePath,fileName];
        WeakObj(self);
        [selfWeak handeleDownload:ftpUrl downFilePath:downFilePath fileName:fileName FtpSuccessdownload:success FtpFailload:failure];
        
       
    } else { //存在解压后文件
        NSLog(@"已存在");
        NSDictionary *dict = [self getUnzipFileName:fileName];
       // NSLog(@"%@",dict);
        if (dict.count==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新
                [MBProgressHUD showText:@"资源下载错误" state:KZHUDStateModeFailure duration:2];
            });
             [self deleteFile:fileName];
             [self deleteUnzip:fileName];
             failure(@"解压文件为空error1");
        } else {
            NSString *unzippath = [NSString stringWithFormat:@"%@%@/%@",NSHomeDirectory(),unzipFilePath,fileName];
            NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:unzippath];
            NSArray *names = [dirEnum allObjects];
            success(dict,names);
        }
        //self.successBlock(dict,names);
    }
}

- (void)handeleDownload:(NSString*)ftpUrl downFilePath:(NSString*)downFilePath fileName:(NSString*)fileName FtpSuccessdownload:(FtpSuccessdownloadBlock)success FtpFailload:(FtpFailloadBlock)failure{
    
    //WeakObj(self);
    [ZBFtpTools ZBFtp_DownloadFileAtRemotePath:ftpUrl toLocalPath:downFilePath percentBlock:^(CGFloat percent) {
        NSLog(@"下载：%@",[NSString stringWithFormat:@"%.2f%%",percent *100]);
    } completeDownload:^{
        NSLog(@"下载完成");
        [self handelUnzipFile:fileName downFilePath:downFilePath FtpSuccessdownload:success FtpFailload:failure];
        
    } requestError:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
           // selfWeak.failBlock(error.description);
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新
                [MBProgressHUD showText:@"资源下载错误" state:KZHUDStateModeFailure duration:2];
            });
            [self deleteFile:fileName];
            [self deleteUnzip:fileName];
            failure(@"error下载失败");
        }
    }];
}

- (void)handelUnzipFile:(NSString*)fileName downFilePath:(NSString*)downFilePath FtpSuccessdownload:(FtpSuccessdownloadBlock)success FtpFailload:(FtpFailloadBlock)failure{
    //解密
    [self decodeAtxzFile:fileName downFilePath:downFilePath];
    //解压
    //[selfWeak unzipFromZipFileName:fileName];
    NSString *zipPath = [NSString stringWithFormat:@"%@%@/%@.zip", NSHomeDirectory(),zipFilePath,fileName];
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@/%@", NSHomeDirectory(),unzipFilePath,fileName];

    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL isDir = YES;
    if(![fm fileExistsAtPath:unzipPath isDirectory:&isDir]) {
        [fm createDirectoryAtPath:unzipPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
   // NSLog(@"unzipPath=%@",unzipPath);

    WeakObj(self);
    [SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath overwrite:YES password:@"" progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {

    } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
        NSDictionary *dict = [selfWeak getUnzipFileName:fileName];
       // NSLog(@"%@",dict);
        
        if(dict.count==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新
                [MBProgressHUD showText:@"数据获取错误" state:KZHUDStateModeFailure duration:2];
            });
            
            [selfWeak deleteFile:fileName];
            [selfWeak deleteUnzip:fileName];
            
            failure(@"解压文件为空error2");
        } else {
            NSLog(@"解压成功");
            [selfWeak deleteFile:fileName];

            NSString *unzippath = [NSString stringWithFormat:@"%@%@/%@",NSHomeDirectory(),unzipFilePath,fileName];
            NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:unzippath];
            NSArray *names = [dirEnum allObjects];

            success(dict,names);
        }
       // selfWeak.successBlock(dict,names);
    }];
}

//- (void)LS_ftpdownloadFileName:(NSString *)fileName Path:(NSString*)ftpUrl Success:(void (^)(NSDictionary *, NSArray *))success failuer:(void (^)(NSString *))failure {
//
//
//
//}
//

#pragma mark - 解密解压处理
//zip文件解密路径处理
- (void)decodeAtxzFile:(NSString*)fileName downFilePath:(NSString*)downFilePath{
    NSString *zipPath = [NSString stringWithFormat:@"%@%@", NSHomeDirectory(),zipFilePath];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL isDir = YES;
    if(![fm fileExistsAtPath:zipPath isDirectory:&isDir]) {
        [fm createDirectoryAtPath:zipPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSLog(@"zipPath=%@",zipPath);
    zipPath = [NSString stringWithFormat:@"%@/%@.zip",zipPath,fileName];
    //解密
    [self decodeWithSourcePath:downFilePath zipPath:zipPath];
    NSLog(@"解密成功");
}

// 解密代码
- (void)decodeWithSourcePath:(NSString*)path zipPath:(NSString*)zipPath {
    //encryptStr-秘钥 path-文件路径 zipPath-解密后压缩包路径
    //秘钥d91077b590a545d296783e1375317670
    //获取key长度
    NSString *encryptStr = @"d91077b590a545d296783e1375317670";
    NSInteger length = encryptStr.length;
    NSInteger bufferSize = length*32*8;
    //转换c字符串
    const char *keys = [encryptStr cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cKey[length];
    memcpy(cKey, keys, length);
    //数据初始化，空间未分配 配合使用 appendBytes
    NSMutableData *encryptData = [[NSMutableData alloc] initWithCapacity:bufferSize];
    // 获取字节指针
    NSData *data = [NSData dataWithContentsOfFile:path];
    const Byte *point = data.bytes;
    for (int i = 0; i < data.length; i++) {
        int l = i % length;
        // 算出当前位置字节，要和密钥的异或运算的密钥字节
        char c = cKey[l];
        Byte b = (Byte) ((point[i]) ^ c);
        // 异或运算
        [encryptData appendBytes:&b length:1];// 追加字节
    }
    // 转成zip到指定目录下
    [encryptData.copy writeToFile:zipPath atomically:YES];
}

//解压文件
- (void)unzipFromZipFileName:(NSString*)fileName {
    NSString *zipPath = [NSString stringWithFormat:@"%@%@/%@.zip", NSHomeDirectory(),zipFilePath,fileName];
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@/%@", NSHomeDirectory(),unzipFilePath,fileName];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL isDir = YES;
    if(![fm fileExistsAtPath:unzipPath isDirectory:&isDir]) {
        [fm createDirectoryAtPath:unzipPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSLog(@"unzipPath=%@",unzipPath);
    
    [SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath overwrite:YES password:@"" progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
        
    } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
        NSDictionary *dict = [self getUnzipFileName:fileName];
        NSLog(@"%@",dict);
        NSLog(@"解压成功");
        [self deleteFile:fileName];
    }];
}

//获取解压后各文件路径
- (NSMutableDictionary*)getUnzipFileName:(NSString*)fileName {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSString *path = [NSString stringWithFormat:@"%@%@/%@",NSHomeDirectory(),unzipFilePath,fileName];
    NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
    NSArray *names = [dirEnum allObjects];
    for (NSString *name in names) {
        if ([name hasSuffix:@"Ques.xml"]) {
            [dict setObject:[NSString stringWithFormat:@"%@/%@",path,name] forKey:@"XML"];
        }
        if ([name hasSuffix:@".mp3"]) {
            [dict setObject:[NSString stringWithFormat:@"%@/%@",path,name] forKey:@"MP3"];
        }
        if ([name hasSuffix:@".mp4"]) {
            [dict setObject:[NSString stringWithFormat:@"%@/%@",path,name] forKey:@"MP4"];
        }
        if ([name hasSuffix:@".txt"]) {
            [dict setObject:[NSString stringWithFormat:@"%@/%@",path,name] forKey:@"TXT"];
        }
        if ([name hasSuffix:@".lrc"]) {
            [dict setObject:[NSString stringWithFormat:@"%@/%@",path,name] forKey:@"LRC"];
        }
    }
    
    return dict;
}

#pragma mark - 删除文件
- (void)deleteFile:(NSString*)fileName {
    NSString *downFilePath = [NSString stringWithFormat:@"%@%@/%@.atxz", NSHomeDirectory(),downloadFilePath,fileName];
    NSString *zipPath = [NSString stringWithFormat:@"%@%@/%@.zip", NSHomeDirectory(),zipFilePath,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager removeItemAtPath:zipPath error:nil] ) {
        NSLog(@"删除压缩包成功");
    }
    if([fileManager removeItemAtPath:downFilePath error:nil] ) {
        NSLog(@"删除atxz文件成功");
    }
}

- (void)deleteUnzip:(NSString*)fileName {
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@/%@", NSHomeDirectory(),unzipFilePath,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager removeItemAtPath:unzipPath error:nil] ) {
        NSLog(@"删除解压文件成功");
    }
}

#pragma mark - 判断解压文件是否存在
- (BOOL)isExistUnzipFile:(NSString*)fileName {
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@/%@", NSHomeDirectory(),unzipFilePath,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDic = YES;
    if([fileManager fileExistsAtPath:unzipPath isDirectory:&isDic]) {
        return YES;
    }
    return NO;
}


@end
